package com.stark.commons.spring.web.support.forest.converter;

import javax.annotation.Nonnull;
import java.text.ParseException;
import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 自定义日期格式化。
 *
 * @author Ben
 * @version 1.0.0
 * @since 2023/8/8
 */
public class DateTimeFormat extends SimpleDateFormat {

    private static final long serialVersionUID = -4925301305082668694L;

    private static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd");

    private static final SimpleDateFormat DATETIME_FORMAT = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    private static final SimpleDateFormat DATETIME_FORMAT1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");

    private static final SimpleDateFormat DATETIME_FORMAT2 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");

    private static final SimpleDateFormat DATETIME_FORMAT3 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS");

    @Override
    public Date parse(String source) throws ParseException {
        try {
            return DATE_FORMAT.parse(source);
        } catch (ParseException  e) {
            // do nothing
        }
        try {
            return DATETIME_FORMAT.parse(source);
        } catch (ParseException  e) {
            // do nothing
        }
        try {
            return DATETIME_FORMAT1.parse(source);
        } catch (ParseException  e) {
            // do nothing
        }
        try {
            return DATETIME_FORMAT2.parse(source);
        } catch (ParseException  e) {
            // do nothing
        }
        return DATETIME_FORMAT3.parse(source);
    }

    @Override
    public Date parse(@Nonnull String text, @Nonnull ParsePosition pos) {
        try {
            return DATE_FORMAT.parse(text, pos);
        } catch (NullPointerException  e) {
            // do nothing
        }
        try {
            return DATETIME_FORMAT.parse(text, pos);
        } catch (NullPointerException  e) {
            // do nothing
        }
        try {
            return DATETIME_FORMAT1.parse(text, pos);
        } catch (NullPointerException  e) {
            // do nothing
        }
        try {
            return DATETIME_FORMAT2.parse(text, pos);
        } catch (NullPointerException  e) {
            // do nothing
        }
        return DATETIME_FORMAT3.parse(text, pos);
    }

}
